<template>
  <div class="dashboard">
    <!-- 页面标题 -->
    <div class="dashboard-header">
      <h1 class="page-title">系统概览</h1>
      <p class="page-description">欢迎使用 Kexilo 权限管理系统</p>
      <div class="refresh-time">
        最后更新时间：{{ refreshTime }}
        <el-button type="primary" size="small" @click="refreshData" :loading="loading">
          刷新数据
        </el-button>
      </div>
    </div>

    <!-- 快捷统计 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6" :xs="12" :sm="12" :md="6">
        <div class="stat-card">
          <div class="stat-icon primary">
            <el-icon><User /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number" v-loading="loading">{{ overview.userCount || 0 }}</div>
            <div class="stat-label">用户总数</div>
            <div class="stat-trend">
              <span class="trend-text">今日新增: {{ overview.todayRegisterCount || 0 }}</span>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :span="6" :xs="12" :sm="12" :md="6">
        <div class="stat-card">
          <div class="stat-icon success">
            <el-icon><UserFilled /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number" v-loading="loading">{{ overview.roleCount || 0 }}</div>
            <div class="stat-label">角色数量</div>
            <div class="stat-trend">
              <span class="trend-text">本周登录: {{ overview.weekLoginCount || 0 }}</span>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :span="6" :xs="12" :sm="12" :md="6">
        <div class="stat-card">
          <div class="stat-icon warning">
            <el-icon><Menu /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number" v-loading="loading">{{ overview.menuCount || 0 }}</div>
            <div class="stat-label">菜单数量</div>
            <div class="stat-trend">
              <span class="trend-text">部门数量: {{ overview.deptCount || 0 }}</span>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :span="6" :xs="12" :sm="12" :md="6">
        <div class="stat-card">
          <div class="stat-icon info">
            <el-icon><Document /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number" v-loading="loading">{{ overview.todayOperCount || 0 }}</div>
            <div class="stat-label">今日操作</div>
            <div class="stat-trend">
              <span class="trend-text">本周操作: {{ overview.weekOperCount || 0 }}</span>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts-row">
      <!-- 登录统计图表 -->
      <el-col :span="12" :xs="24">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>登录统计（近7天）</span>
              <el-button size="small" @click="refreshLoginStats">刷新</el-button>
            </div>
          </template>
          <div ref="loginChartRef" class="chart-container"></div>
        </el-card>
      </el-col>

      <!-- 操作统计图表 -->
      <el-col :span="12" :xs="24">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>操作统计（近7天）</span>
              <el-button size="small" @click="refreshOperationStats">刷新</el-button>
            </div>
          </template>
          <div ref="operationChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 详细统计 -->
    <el-row :gutter="20" class="detail-row">
      <!-- 用户状态分布 -->
      <el-col :span="8" :xs="24">
        <el-card class="detail-card">
          <template #header>
            <div class="card-header">
              <span>用户状态分布</span>
            </div>
          </template>
          <div ref="userStatusChartRef" class="chart-container-small"></div>
        </el-card>
      </el-col>

      <!-- 操作类型统计 -->
      <el-col :span="8" :xs="24">
        <el-card class="detail-card">
          <template #header>
            <div class="card-header">
              <span>操作类型统计</span>
            </div>
          </template>
          <div ref="operationTypeChartRef" class="chart-container-small"></div>
        </el-card>
      </el-col>

      <!-- 最近操作记录 -->
      <el-col :span="8" :xs="24">
        <el-card class="detail-card">
          <template #header>
            <div class="card-header">
              <span>最近操作记录</span>
              <el-link type="primary" href="/monitor/operlog">查看更多</el-link>
            </div>
          </template>
          <div class="recent-operations">
            <div v-for="(item, index) in recentOperations" :key="index" class="operation-item">
              <div class="operation-user">{{ item.operName }}</div>
              <div class="operation-desc">{{ item.title }}</div>
              <div class="operation-time">{{ item.operTime }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 快捷操作 -->
    <el-row :gutter="20" class="quick-actions-row">
      <el-col :span="24">
        <el-card class="quick-actions-card">
          <template #header>
            <div class="card-header">
              <span>快捷操作</span>
            </div>
          </template>
          <div class="quick-actions">
            <el-button type="primary" icon="Plus" @click="$router.push('/system/user')">
              新增用户
            </el-button>
            <el-button type="success" icon="Plus" @click="$router.push('/system/role')">
              新增角色
            </el-button>
            <el-button type="warning" icon="Plus" @click="$router.push('/system/menu')">
              新增菜单
            </el-button>
            <el-button type="info" icon="Monitor" @click="$router.push('/monitor/server')">
              系统监控
            </el-button>
            <el-button type="danger" icon="Document" @click="$router.push('/monitor/operlog')">
              操作日志
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import * as echarts from 'echarts'
import {
  getDashboardOverview,
  getLoginStats,
  getOperationStats,
  getUserStats,
} from '@/api/dashboard'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const refreshTime = ref('')
const overview = reactive<any>({})
const loginStats = reactive<any>({})
const operationStats = reactive<any>({})
const userStats = reactive<any>({})
const recentOperations = ref<any[]>([])

// 图表实例
const loginChartRef = ref()
const operationChartRef = ref()
const userStatusChartRef = ref()
const operationTypeChartRef = ref()
let loginChart: echarts.ECharts
let operationChart: echarts.ECharts
let userStatusChart: echarts.ECharts
let operationTypeChart: echarts.ECharts

// 获取概览数据
const getOverviewData = async () => {
  try {
    const { data } = await getDashboardOverview()
    Object.assign(overview, data)
  } catch (error) {
    console.error('获取概览数据失败:', error)
    ElMessage.error('获取概览数据失败')
  }
}

// 获取登录统计数据
const getLoginStatsData = async () => {
  try {
    const { data } = await getLoginStats()
    Object.assign(loginStats, data)
    nextTick(() => {
      renderLoginChart()
    })
  } catch (error) {
    console.error('获取登录统计失败:', error)
  }
}

// 获取操作统计数据
const getOperationStatsData = async () => {
  try {
    const { data } = await getOperationStats()
    Object.assign(operationStats, data)
    nextTick(() => {
      renderOperationChart()
      renderOperationTypeChart()
    })
  } catch (error) {
    console.error('获取操作统计失败:', error)
  }
}

// 获取用户统计数据
const getUserStatsData = async () => {
  try {
    const { data } = await getUserStats()
    Object.assign(userStats, data)
    nextTick(() => {
      renderUserStatusChart()
    })
  } catch (error) {
    console.error('获取用户统计失败:', error)
  }
}

// 渲染登录统计图表
const renderLoginChart = () => {
  if (!loginChartRef.value || !loginStats.weeklyStats) return
  
  if (!loginChart) {
    loginChart = echarts.init(loginChartRef.value)
  }
  
  const dates = loginStats.weeklyStats.map((item: any) => item.date)
  const loginCounts = loginStats.weeklyStats.map((item: any) => item.loginCount)
  const successCounts = loginStats.weeklyStats.map((item: any) => item.successCount)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      data: ['总登录', '成功登录']
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: dates
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '总登录',
        type: 'line',
        stack: 'Total',
        data: loginCounts,
        itemStyle: {
          color: '#409EFF'
        }
      },
      {
        name: '成功登录',
        type: 'line',
        stack: 'Total',
        data: successCounts,
        itemStyle: {
          color: '#67C23A'
        }
      }
    ]
  }
  
  loginChart.setOption(option)
}

// 渲染操作统计图表
const renderOperationChart = () => {
  if (!operationChartRef.value || !operationStats.weeklyStats) return
  
  if (!operationChart) {
    operationChart = echarts.init(operationChartRef.value)
  }
  
  const dates = operationStats.weeklyStats.map((item: any) => item.date)
  const operCounts = operationStats.weeklyStats.map((item: any) => item.operCount)
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: dates
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: operCounts,
        type: 'bar',
        itemStyle: {
          color: '#E6A23C'
        }
      }
    ]
  }
  
  operationChart.setOption(option)
}

// 渲染用户状态分布图表
const renderUserStatusChart = () => {
  if (!userStatusChartRef.value || !userStats.statusStats) return
  
  if (!userStatusChart) {
    userStatusChart = echarts.init(userStatusChartRef.value)
  }
  
  const option = {
    tooltip: {
      trigger: 'item'
    },
    series: [
      {
        type: 'pie',
        radius: '50%',
        data: [
          { value: userStats.statusStats.activeCount, name: '正常用户' },
          { value: userStats.statusStats.inactiveCount, name: '停用用户' }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  
  userStatusChart.setOption(option)
}

// 渲染操作类型统计图表
const renderOperationTypeChart = () => {
  if (!operationTypeChartRef.value || !operationStats.typeStats) return
  
  if (!operationTypeChart) {
    operationTypeChart = echarts.init(operationTypeChartRef.value)
  }
  
  const option = {
    tooltip: {
      trigger: 'item'
    },
    series: [
      {
        type: 'pie',
        radius: '50%',
        data: [
          { value: operationStats.typeStats.insertCount, name: '新增' },
          { value: operationStats.typeStats.updateCount, name: '修改' },
          { value: operationStats.typeStats.deleteCount, name: '删除' },
          { value: operationStats.typeStats.exportCount, name: '导出' }
        ]
      }
    ]
  }
  
  operationTypeChart.setOption(option)
}

// 刷新所有数据
const refreshData = async () => {
  loading.value = true
  try {
    await Promise.all([
      getOverviewData(),
      getLoginStatsData(),
      getOperationStatsData(),
      getUserStatsData(),
    ])
    refreshTime.value = new Date().toLocaleString()
    ElMessage.success('数据刷新成功')
  } catch (error) {
    ElMessage.error('数据刷新失败')
  } finally {
    loading.value = false
  }
}

// 刷新登录统计
const refreshLoginStats = () => {
  getLoginStatsData()
}

// 刷新操作统计
const refreshOperationStats = () => {
  getOperationStatsData()
}

// 模拟最近操作数据
const getMockRecentOperations = () => {
  recentOperations.value = [
    { operName: '管理员', title: '用户管理', operTime: '2024-01-15 10:30' },
    { operName: '张三', title: '角色分配', operTime: '2024-01-15 10:25' },
    { operName: '李四', title: '菜单配置', operTime: '2024-01-15 10:20' },
    { operName: '王五', title: '系统配置', operTime: '2024-01-15 10:15' },
    { operName: '赵六', title: '日志查看', operTime: '2024-01-15 10:10' },
  ]
}

// 窗口调整时重新渲染图表
const handleResize = () => {
  loginChart?.resize()
  operationChart?.resize()
  userStatusChart?.resize()
  operationTypeChart?.resize()
}

// 生命周期
onMounted(() => {
  refreshData()
  getMockRecentOperations()
  
  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
})
</script>

<style lang="scss" scoped>
.dashboard {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 84px);
}

.dashboard-header {
  text-align: center;
  margin-bottom: 30px;
  
  .page-title {
    font-size: 28px;
    font-weight: 600;
    color: #303133;
    margin: 0 0 10px 0;
  }
  
  .page-description {
    font-size: 16px;
    color: #606266;
    margin: 0 0 20px 0;
  }
  
  .refresh-time {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 12px;
    font-size: 14px;
    color: #909399;
  }
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
  
  &:hover {
    box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.15);
    transform: translateY(-2px);
  }
  
  .stat-icon {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 16px;
    
    .el-icon {
      font-size: 24px;
      color: white;
    }
    
    &.primary {
      background: linear-gradient(135deg, #409EFF, #6BB7FF);
    }
    
    &.success {
      background: linear-gradient(135deg, #67C23A, #95D475);
    }
    
    &.warning {
      background: linear-gradient(135deg, #E6A23C, #F0C674);
    }
    
    &.info {
      background: linear-gradient(135deg, #909399, #B1B3B8);
    }
  }
  
  .stat-content {
    flex: 1;
    
    .stat-number {
      font-size: 28px;
      font-weight: 600;
      color: #303133;
      margin-bottom: 5px;
    }
    
    .stat-label {
      font-size: 14px;
      color: #606266;
      margin-bottom: 5px;
    }
    
    .stat-trend {
      .trend-text {
        font-size: 12px;
        color: #909399;
      }
    }
  }
}

.charts-row,
.detail-row,
.quick-actions-row {
  margin-bottom: 20px;
}

.chart-card,
.detail-card,
.quick-actions-card {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: 600;
  }
}

.chart-container {
  width: 100%;
  height: 300px;
}

.chart-container-small {
  width: 100%;
  height: 200px;
}

.recent-operations {
  .operation-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 0;
    border-bottom: 1px solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    .operation-user {
      font-weight: 500;
      color: #303133;
    }
    
    .operation-desc {
      flex: 1;
      text-align: center;
      color: #606266;
    }
    
    .operation-time {
      font-size: 12px;
      color: #909399;
    }
  }
}

.quick-actions {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

// 响应式设计
@media (max-width: 768px) {
  .dashboard {
    padding: 10px;
  }
  
  .dashboard-header {
    .refresh-time {
      flex-direction: column;
      gap: 8px;
    }
  }
  
  .stat-card {
    padding: 15px;
    
    .stat-icon {
      width: 50px;
      height: 50px;
      margin-right: 12px;
      
      .el-icon {
        font-size: 20px;
      }
    }
    
    .stat-content {
      .stat-number {
        font-size: 24px;
      }
    }
  }
  
  .quick-actions {
    justify-content: center;
  }
  
  .chart-container {
    height: 250px;
  }
  
  .chart-container-small {
    height: 180px;
  }
}
</style>